package logic

import (
	"context"
	"github.com/pkg/errors"
	"mall/app/auth/cmd/api/internal/constant"
	"mall/app/member/cmd/rpc/pb"
	"mall/common/xerr"
	"strings"

	"mall/app/auth/cmd/api/internal/svc"
	"mall/app/auth/cmd/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterReq) error {
	// 校验验证码
	key := constant.SMS_CODE_CACHE_PREFIX + req.Phone
	val, err := l.svcCtx.RedisClient.GetCtx(l.ctx, key)
	if err != nil {
		return err
	}
	if val != "" {
		if strings.Split(val, "*")[0] == req.Code {
			// 调用member完成注册
			_, err = l.svcCtx.MemberRpc.Register(l.ctx, &pb.RegisterReq{UserName: req.UserName, Password: req.Password, Phone: req.Phone})
			if err != nil {
				return errors.Wrapf(xerr.NewErrorWithMsg("注册失败"), "MemberRpc.Register err: +%v", err)
			}
			// 删除验证码
			_, err = l.svcCtx.RedisClient.DelCtx(l.ctx, key)
			if err != nil {
				return errors.Wrapf(xerr.NewErrorWithCode(xerr.ServerError), "删除验证码失败 err: %+v", err)
			}
		} else {
			return errors.Wrapf(xerr.NewErrorWithCode(xerr.SmsCodeErr), "验证码错误")
		}
	} else {
		return errors.Wrapf(xerr.NewErrorWithCode(xerr.SmsCodeErr), "验证码错误")
	}
	return nil
}
